package com.qkl.xiatang.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.vedia.DahuaResponse;
import com.qkl.xiatang.app.dto.vedia.DahuaTokenResponse;
import com.qkl.xiatang.app.entity.video.DahuaConfigEntity;
import com.qkl.xiatang.app.mapper.DahuaConfigMapper;
import com.qkl.xiatang.app.utils.DahuaUtils;
import com.qkl.xiatang.app.utils.HttpResponse;
import com.qkl.xiatang.app.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DahuaService {

    private static final String URL_GET_TOKEN = "/api-base/auth/getAppAccessToken";

    @Autowired
    private DahuaConfigMapper dahuaConfigMapper;

    /**
     * 获取大华访问token
     * @return
     */
    public BusinessDTO<DahuaConfigEntity> getDahuaToken(){
        DahuaConfigEntity queryEntity = this.getConfig();
        if(null == queryEntity){
            return BusinessDTO.failBusiness("大华云未配置");
        }
        if( !queryEntity.tokenValidity()){
            log.info("==== getToken by cache.缓存token");
            return BusinessDTO.sucessBusiness(queryEntity,"获取大华访问token");
        }
        Integer id = queryEntity.getId();
        String productId = StringUtils.trimToEmpty(queryEntity.getProductId());
        String accessKey = StringUtils.trimToEmpty(queryEntity.getAccessKey());
        String secretAccessKey = StringUtils.trimToEmpty(queryEntity.getSecretAccessKey());
        String apiDomain = StringUtils.trimToEmpty(queryEntity.getApiDomain());
        if(StringUtils.isAnyEmpty(productId,accessKey,secretAccessKey,apiDomain)){
            return BusinessDTO.failBusiness("大华云 产品id 或 子域名 等未配置");
        }
        String url = apiDomain + URL_GET_TOKEN;
        DahuaResponse<DahuaTokenResponse>  tokenResponse = this.getToken(url,accessKey,secretAccessKey,productId);
        if(!tokenResponse.isSuccess()){
            return BusinessDTO.failBusiness(tokenResponse.getMsg());
        }
        if(null == tokenResponse.getData() || StringUtils.isEmpty(tokenResponse.getData().getAppAccessToken())){
            return BusinessDTO.failBusiness("大华云token为空");
        }
        DahuaConfigEntity updEntity = new DahuaConfigEntity();
        updEntity.setId(id);
        updEntity.setAccessToken(tokenResponse.getData().getAppAccessToken());
        updEntity.setValiditySeconds(tokenResponse.getData().getValiditySeconds());
        updEntity.setTokenTime(System.currentTimeMillis());
        dahuaConfigMapper.updateById(updEntity);

        queryEntity.setTokenTime(updEntity.getTokenTime());
        queryEntity.setValiditySeconds(updEntity.getValiditySeconds());
        queryEntity.setAccessKey(updEntity.getAccessKey());
        return BusinessDTO.sucessBusiness(queryEntity,"获取大华访问token");
    }

    private DahuaResponse<DahuaTokenResponse> getToken(String url,String accessKey,String secretAccessKey,String productID){
        Map<String,Object> body = new HashMap<>();
        body.put("grantType",1);

        String httpMethod = "POST";
        long timestamp = DahuaUtils.timestamp();
        String nonce = DahuaUtils.nonce();
        String stringToSign = DahuaUtils.stringToSign(httpMethod,body,null);
        String sign = DahuaUtils.sign(accessKey,timestamp,nonce,stringToSign,secretAccessKey);
        Map<String, String> headers = DahuaUtils.toHeaders(accessKey,timestamp,nonce,sign,productID);

        //HttpResponse<String> response = HttpUtils.getRequest(url,null,headers);
        HttpResponse<String> response = HttpUtils.postRequestJson(url,headers,body);
        if(response.isSuccess()){
            String data = response.getData();
            return JSON.parseObject(data, new TypeReference<DahuaResponse<DahuaTokenResponse>>(){});
        }
        DahuaResponse<DahuaTokenResponse> errorResponse = new DahuaResponse<>();
        errorResponse.setCode("7777");
        errorResponse.setMsg(response.getMsg());
        errorResponse.setSuccess(false);
        return errorResponse;
    }

    private DahuaConfigEntity getConfig(){
        List<DahuaConfigEntity> list = dahuaConfigMapper.selectList(null);
        if(ObjectUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

}
